<?php

declare(strict_types=1);

namespace App\Server;

use App\Library\MySeasLog;
use Hyperf\Logger\LoggerFactory;
use Psr\Log\LoggerInterface;
use Swoole\Server;

class TcpServer
{
    private LoggerInterface $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        $this->logger = $loggerFactory->get();
    }

    /**
     * 当客户端连接时触发
     * @param Server $server
     * @param int $fd
     * @param int $reactorId
     * @return void
     */
    public function onConnect(Server $server, int $fd, int $reactorId): void
    {
        $context = [$fd, $reactorId];
        $this->logger->info('客户端已连接', $context);
        $server->send($fd, '欢迎连接到 Hyperf TCP 服务');
    }

    /**
     * 当收到客户端数据时触发
     * @param Server $server
     * @param int $fd
     * @param int $reactorId
     * @param string $data
     * @return void
     */
    public function onReceive(Server $server, int $fd, int $reactorId, string $data): void
    {
        $context = [$fd, $reactorId, $data];
        $this->logger->info('收到客户端的数据', $context);
        MySeasLog::writer($context);
        $server->send($fd, '已收到:' . $data);#简单的回声服务
        #如果收到 'quit' 则关闭连接
        if (trim($data) === 'quit') {
            $server->send($fd, '正在断开连接...');
            $this->logger->info('正在断开连接...', $context);
            $server->close($fd);
        }
    }

    /**
     * 当客户端断开连接时触发
     * @param Server $server
     * @param int $fd
     * @param int $reactorId
     * @return void
     */
    public function onClose(Server $server, int $fd, int $reactorId): void
    {
        $context = [$fd, $reactorId];
        $this->logger->info('客户端已断开连接...', $context);
    }
}
